package com.lagou.edu.utils;

import com.lagou.edu.annotations.Component;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 当前线程绑定唯一数据库连接
 */
@Component("connectionUtils")
public class ConnectionUtils {

    //存储当前线程的数据库连接
    private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    /**
     * 从当前线程获取唯一数据库连接
     *
     * @return
     */
    public Connection getConnection() throws SQLException {
        Connection connection = threadLocal.get();
        if (connection == null) {
            //当前线程连接为空,获取一个新连接
            connection = DruidUtils.getInstance().getConnection();
            //设置到当前线程中
            threadLocal.set(connection);

        }
        return connection;
    }
}
